import SelectCity from '@/util/provinces.vue';
import vSwitch from '@/util/vSwitch.vue';
import util from '@/libs/util';
import Cookies from 'js-cookie';
import orgtable from './orgTable.vue';
import CONSTANTS from '@/config/constants';

export default {
    components: {
        SelectCity, orgtable, vSwitch
    },
    props: {
        query: {},
        cityinfo: {},
        parentid: '',
        orgselect: '',
        level: ''
    },
    data () {
        return {
            baseuser: JSON.parse(Cookies.get('baseUser')),
            columns: [{
                type: 'expand',
                width: 40,
                render: (h, params) => {
                    return h(orgtable, {
                        props: {
                            parentid: params.row.id,
                            level: (1 + (this.level * 1))
                        }
                    });
                }
            }, {
                title: '机构/部门名称',
                key: 'name',
                render: (h, params) => {
                    var margin = (this.level * 10) + 'px';
                    return h('div', {
                        style: {
                            marginLeft: margin
                        }
                    }, params.row.name);
                }

            }, {
                title: '归属区域',
                key: 'attribution'
            }, {
                title: '机构类型',
                key: 'type',
                render: (h, params) => {
                    let text = params.row.type == 1 ? '机构' : '部门';
                    return h('div', {}, text);
                }
            }, {
                title: '状态',
                key: 'status',
                render: (h, params) => {
                    return h(vSwitch, {
                        props: {
                            vStatus: params.row.status === 1
                        },
                        on: {
                            input: (switchVal) => {
                                this.changeStatus(params.row, switchVal);
                            }
                        }
                    });
                }
            }, {
                title: '操作',
                key: 'action',
                align: 'center',
                width: 300,
                render: (h, params) => {
                    return h('div', [
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.isRead = true;
                                    if (params.row.type === 1) {
                                        this.showEdit(params.row);
                                    } else {
                                        this.showEditChild(params.row);
                                    }
                                }
                            }
                        }, '详情'),
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.isRead = false;
                                    if (params.row.type === 1) {
                                        this.showEdit(params.row);
                                    } else {
                                        this.showEditChild(params.row);
                                    }
                                }
                            }
                        }, '修改'),
                        h('Button', {
                            props: {
                                type: 'error',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.delete(params.row.id);
                                }
                            }
                        }, '删除'),
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.isRead = false;
                                    this.showAddChild(params.row);
                                }
                            }
                        }, '添加下级部门')
                    ]);
                }
            }],
            dataList: [],
            options: {
                shortcuts: [{
                    text: '今天',
                    value () {
                        return new Date();
                    }
                }]
            },
            pageIndex: 1,
            pageSize: 10,
            total: 0,
            formData: {},
            editModal: false,
            natureList: [],
            orgList: [],
            editCity: {},
            butSave: false,

            SERVER_HOST: CONSTANTS.SERVER_HOST,
            imgModal: false,
            imgPath: '',
            uploadingList: '',
            uploadRef: '',
            codepapersList: [],
            businessList: [],
            legalpersonList: [],
            contractList: [],

            childModal: false,
            childForm: {},
            isRead: false
        };
    },
    mounted () {
        if (this.parentid) {
            this.loadChild();
        } else {
            this.loadOrg();
            this.loadNature();
            this.loadList();
        }
    },
    methods: {
        loadNature () {
            util.ajax.post('/base/datadictionary/findByCode', util.toFormData({
                CODE: 'ORGNATURE_TYPE'
            })).then(res => {
                if (res.data.data) {
                    this.natureList = res.data.data;
                }
            });
        },
        loadOrg () {
            util.ajax.post('/base/organize/findOrg', util.toFormData()).then(res => {
                if (res.data.data) {
                    this.orgList = res.data.data;
                }
            });
        },
        loadList () {
            if (this.parentid) {
                this.loadChild();
                return;
            }
            let queryData = {};
            for (var key in this.query) {
                queryData[key] = this.query[key];
            }
            if(this.baseuser.type==1){
                queryData['orgid'] = '';
            }else{
                queryData['orgid'] = this.baseuser.orgId;
            }
            if (queryData['startDate']) queryData['startDate'] = util.getDate(queryData['startDate'], 'date');
            if (queryData['endDate']) queryData['endDate'] = util.getDate(queryData['endDate'], 'date');
            if (this.cityinfo.province) queryData['province'] = this.cityinfo.province.code || '';
            if (this.cityinfo.city) queryData['city'] = this.cityinfo.city.code || '';
            if (this.cityinfo.block) queryData['block'] = this.cityinfo.block.code || '';
            queryData['orgselect'] = this.orgselect;
            util.ajax.post('/base/organize/list', util.toFormData(queryData)).then(res => {
                if (res.data.data) {
                    this.dataList = res.data.data.list;
                    this.total = res.data.data.total;
                    this.dataList.forEach(item => {
                        item._disableExpand = !item.havechild;
                    });
                }
            });

        },
        loadChild () {
            util.ajax.post('/base/organize/listByParent', util.toFormData({
                parentid: this.parentid
            })).then(res => {
                if (res.data.data) {
                    this.dataList = res.data.data;
                    this.dataList.forEach(item => {
                        item._disableExpand = !item.havechild;
                    });
                }
            });
        },
        showAdd () {
            this.isRead = false;
            this.codepapersList = [];
            this.businessList = [];
            this.legalpersonList = [];
            this.contractList = [];
            this.formData = {
                type: 1,
                parentid: this.baseuser.orgId
            };
            this.editCity = {
                province: '',
                city: '',
                block: ''
            };
            this.editModal = true;
        },
        showEdit (obj) {
            for (var key in obj) {
                this.formData[key] = obj[key];
            }
            this.formData['contractstartdate'] = util.getDate(this.formData.contractstartdate, 'time');
            this.formData['contractenddate'] = util.getDate(this.formData.contractenddate, 'time');
            this.formData['chargestartdate'] = util.getDate(this.formData.chargestartdate, 'time');
            this.formData['chargeenddate'] = util.getDate(this.formData.chargeenddate, 'time');

            // 机构组织机构代码证
            if (this.formData.codepapers) {
                this.codepapersList = [];
                this.$refs.codepapers.fileList = [];
                let list = this.formData.codepapers.split('@');
                list.forEach(item => {
                    this.codepapersList.push({
                        status: 'finished',
                        'url': this.SERVER_HOST + item,
                        path: item
                    });
                });
            } else {
                this.codepapersList = this.$refs.codepapers.fileList = [];
            }
            // 机构营业执照
            if (this.formData.business) {
                this.businessList = [];
                this.$refs.business.fileList = [];
                let list = this.formData.business.split('@');
                list.forEach(item => {
                    this.businessList.push({
                        status: 'finished',
                        'url': this.SERVER_HOST + item,
                        path: item
                    });
                });
            } else {
                this.businessList = this.$refs.business.fileList = [];
            }
            // 机构法人证
            if (this.formData.legalperson) {
                this.legalpersonList = [];
                this.$refs.legalperson.fileList = [];
                let list = this.formData.legalperson.split('@');
                list.forEach(item => {
                    this.legalpersonList.push({
                        status: 'finished',
                        'url': this.SERVER_HOST + item,
                        path: item
                    });
                });
            } else {
                this.legalpersonList = this.$refs.legalperson.fileList = [];
            }

            // 合同
            if (this.formData.contract) {
                this.contractList = [];
                this.$refs.contract.fileList = [];
                this.contractList.push({
                    status: 'finished',
                    'url': this.SERVER_HOST + this.formData.contract,
                    path: this.formData.contract
                });
            } else {
                this.contractList = this.$refs.contract.fileList = [];
            }
            this.editCity = {
                province: this.formData.province,
                city: this.formData.city,
                block: this.formData.block
            };
            this.editModal = true;
        },
        save () {
            let fromData = this.handleFrom();
            if (!fromData) return;
            util.ajax.post('/base/organize/save', util.toFormData(fromData)).then(res => {
                if (res.data.message === 'SUCCESS') {
                    this.editModal = false;
                    this.$Message.success('保存成功！');
                    this.loadList();
                } else {
                    this.$Message.warning(res.data.message || '未知错误！');
                }
            });
        },
        delete (id) {
            this.$Modal.confirm({
                content: '确定删除吗，此操作会影响其下子机构！',
                onOk: () => {
                    util.ajax.post('/base/organize/deleteByParent', util.toFormData({
                        id: id
                    })).then(res => {
                        if (res.data.message === 'SUCCESS') {
                            this.$Message.success('删除成功！');
                            this.loadList();
                        } else {
                            this.$Message.warning(res.data.message || '未知错误！');
                        }
                    });
                }
            });
        },
        handleFrom () {
            let numreg = /^\+?[1-9][0-9]*$/;
            let mobilePhonereg = /^(((17[0-9]{1})|(13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
            let fixedPhonereg = /0\d{2,3}-\d{7,8}/;
            let formData = {};
            for (var key in this.formData) {
                formData[key] = this.formData[key];
            }
            formData['province'] = this.$refs.editCity.province.code || '';
            formData['city'] = this.$refs.editCity.city.code || '';
            formData['block'] = this.$refs.editCity.block.code || '';
            formData['attribution'] = (this.$refs.editCity.province.name || '') + (this.$refs.editCity.city.name || '') + (this.$refs.editCity.block.name || '');
            formData['contractstartdate'] = util.getDate(formData.contractstartdate, 'time');
            formData['contractenddate'] = util.getDate(formData.contractenddate, 'time');
            formData['chargestartdate'] = util.getDate(formData.chargestartdate, 'time');
            formData['chargeenddate'] = util.getDate(formData.chargeenddate, 'time');
            formData['usetype'] = formData['usetype'] ? formData['usetype'] : '';
            formData['type'] = formData['type'] ? formData['type'] : '';
            formData['natureid'] = formData['natureid'] ? formData['natureid'] : '';
            formData['parentid'] = formData['parentid'] ? formData['parentid'] : '';
            if (formData.province === '' || formData.city === '') {
                this.$Modal.error({content: '归属区域省、市不能为空！'});
                return false;
            }
            if (!formData.name) {
                this.$Modal.error({content: '机构名称不能为空！'});
                return false;
            }
            if (!formData.orders) {
                this.$Modal.error({content: '请设置排序！'});
                return false;
            }
            if (!numreg.test(formData.orders)) {
                this.$Modal.error({content: '排序只能为正整数！'});
                return false;
            }
            if (formData.orgphone) {
                if (!mobilePhonereg.test(formData.orgphone) && !fixedPhonereg.test(formData.orgphone)) {
                    this.$Modal.error({content: '请输入有效的机构电话！'});
                    return false;
                }
            }
            if (formData.phone) {
                if (!mobilePhonereg.test(formData.phone)) {
                    this.$Modal.error({content: '请输入有效的负责人电话！'});
                    return false;
                }
            }
            if (!formData.contractstartdate) {
                this.$Modal.error({content: '请设置合同开始时间！'});
                return false;
            }
            if (!formData.contractenddate) {
                this.$Modal.error({content: '请设置合同结束时间！'});
                return false;
            }
            if (formData.contractenddate < formData.contractstartdate) {
                this.$Modal.error({content: '合同结束时间不能小于合同开始时间！'});
                return false;
            }
            if (!formData.chargestartdate) {
                this.$Modal.error({content: '请设置费用开始时间！'});
                return false;
            }
            if (!formData.chargeenddate) {
                this.$Modal.error({content: '请设置费用结束时间！'});
                return false;
            }
            if (formData.chargeenddate < formData.chargestartdate) {
                this.$Modal.error({content: '费用结束时间不能小于费用开始时间！'});
                return false;
            }
            return formData;
        },
        showImg (imgPath) {
            this.imgModal = true;
            this.imgPath = imgPath;
        },
        handleSuccess (res, file) {
            let strUrls = '';
            this[this.uploadingList].forEach(item => {
                strUrls += (item.path + '@');
            });

            this[this.uploadingList].push({
                showProgress: true
            });
            var listSize = this[this.uploadingList].length;
            var xmlhttp = null;
            var urlPath = this.SERVER_HOST + res.data.imgUrl;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            }
            let interval = setInterval(() => {
                xmlhttp.open('GET', urlPath, false);
                xmlhttp.send();
                if ((xmlhttp.readyState === 4 && xmlhttp.status === 200)) {
                    clearInterval(interval);
                    this.$Notice.success({
                        title: '文件上传成功',
                        desc: '文件 ' + file.name + ' 上传成功。',
                        duration: 2
                    });
                    file['path'] = res.data.imgUrl;
                    file['url'] = this.SERVER_HOST + res.data.imgUrl;
                    file['name'] = res.data.fileName;
                    this.butSave = false;

                    if (this.uploadRef === 'contract') {
                        this.contractList = [{
                            url: this.SERVER_HOST + res.data.imgUrl
                        }];
                        this.formData['contract'] = res.data.imgUrl;
                    } else {
                        this.$refs[this.uploadRef].fileList[listSize - 1] = file;
                        this[this.uploadingList].splice(-1, 1, this.$refs[this.uploadRef].fileList[listSize - 1]);
                        strUrls += res.data.imgUrl;
                        this.formData[this.uploadRef] = strUrls;
                    }
                }
            }, 500);
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确。',
                duration: 5
            });
            this.butSave = false;
        },
        handleMaxSize (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。',
                duration: 5
            });
            this.butSave = false;
        },
        handleRemove (ref, upList, file, index) {
            this.uploadRef = ref;
            this.uploadingList = upList;
            this[this.uploadingList].splice(index, 1);
            this.$refs[this.uploadRef].fileList.splice(index, 1);
            let strUrls = '';
            this[this.uploadingList].forEach(item => {
                if (strUrls !== '') strUrls += '@';
                strUrls += item.path;
            });
            this.formData[this.uploadRef] = strUrls;
        },
        handleBeforeUpload (file) {
            this.butSave = true;
            return true;
        },
        uploadClick (ref, list) {
            this.uploadingList = list;
            this.uploadRef = ref;
        },
        changeStatus (obj, switchVal) {
            this.formData['id'] = obj.id;
            this.formData['status'] = 2;
            if (switchVal) this.formData['status'] = 1;

            util.ajax.post('/base/organize/updateByParent', util.toFormData(this.formData)).then(res => {
                if (res.data.message === 'SUCCESS') {
                    this.$Message.success('修改成功！');
                    this.loadList();
                } else {
                    this.$Message.warning(res.data.message || '未知错误！');
                }
            });
        },
        showAddChild (obj) {
            this.childForm = {
                parentid: obj.id,
                parentname: obj.name,
                type: 2,
                province: obj.province,
                city: obj.city,
                block: obj.block,
                attribution: obj.attribution
            };
            this.childModal = true;
        },
        showEditChild (obj) {
            util.ajax.post('/base/organize/detail', util.toFormData({
                id: obj.parentid
            })).then(res => {
                if (res.data.data) {
                    let parentOrg = res.data.data;
                    for (var key in obj) {
                        this.childForm[key] = obj[key];
                    }
                    this.childForm['parentname'] = parentOrg.name;
                    this.childModal = true;
                }
            });
        },
        saveChild () {
            let numreg = /^\+?[1-9][0-9]*$/;
            let formData = {};
            for (var key in this.childForm) {
                formData[key] = this.childForm[key];
            }
            if (!formData.parentid) {
                this.$Modal.error({content: '上级机构不能为空！'});
                return false;
            }
            if (!formData.name) {
                this.$Modal.error({content: '机构名称不能为空！'});
                return false;
            }
            if (!formData.orders) {
                this.$Modal.error({content: '请设置排序！'});
                return false;
            }
            if (!numreg.test(formData.orders)) {
                this.$Modal.error({content: '排序只能为正整数！'});
                return false;
            }
            util.ajax.post('/base/organize/save', util.toFormData(formData)).then(res => {
                if (res.data.message === 'SUCCESS') {
                    this.childModal = false;
                    this.$Message.success('保存成功！');
                    this.loadList();
                } else {
                    this.$Message.warning(res.data.message || '未知错误！');
                }
            });
        }
    }
};
